# app/routes/assignments.py
import os

from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, app, current_app, abort
from sqlalchemy import text
from flask_login import current_user
from werkzeug.utils import secure_filename
from flask import send_from_directory
from app import db
from app.models import Assignments, Classes

assignments = Blueprint('assignments', __name__)
# app.config['UPLOAD_FOLDER'] = 'uploads/assignment/'

# 文件上传的根目录
UPLOAD_FOLDER = os.path.join(os.getcwd(), 'uploads/assignment/')
UPLOAD_FOLDER2 = os.path.join(os.getcwd(), 'uploads/submissions/')
@assignments.route('/assignment/download/<path:filepath>')
def download_file(filepath):
    try:
        print("文件路径", filepath)
        # 检查文件是否存在
        return send_from_directory(UPLOAD_FOLDER, filepath, as_attachment=True)
    except FileNotFoundError:
        abort(404)  # 如果文件不存在，返回 404 错误

@assignments.route('/assignment/new/<int:id>')
def new_assignment(id):
    return render_template('assignments/set_assignment.html', class_id=id)

@assignments.route('/assignment/upload')
def upload_file():
    return render_template('assignments/upload.html')
@assignments.route('/assignment/set_assignment', methods=['GET', 'POST'])
def set_assignment():
    if request.method == 'POST':
        # 提取文本字段
        assignmentTitle = request.form.get('assignmentTitle')
        assignmentContent = request.form.get('assignmentContent')
        file = request.files.get('file')
        class_id = request.form.get('class_id')
        weight = request.form.get('weight')
        print("1:", assignmentTitle)
        print("2:", assignmentContent)
        print("3:", file)
        print("4:", class_id)
        print("5:", weight)

        filename = ""
        if file:
            print(3333)
            # 确保文件名安全
            filename = secure_filename(file.filename)

            # 构建文件保存路径
            file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
            print("文件名为：", filename)
            print("文件路径为：", file_path)

            # 保存文件
            try:
                file.save(file_path)
            except Exception as e:
                return jsonify({'error': str(e)}), 500

        db.session.execute(text("""
                INSERT INTO assignments (class_id, title, content, file_path, weight) 
                VALUES (:class_id, :title, :content, :filename, :weight)
            """), {'class_id': class_id, 'title': assignmentTitle, 'content': assignmentContent, 'filename': filename, 'weight': weight})
        db.session.commit()

        return jsonify({'message': '作业布置成功'}), 200
    return jsonify({'error': 'Invalid request method'}), 405

@assignments.route('/assignments')
def list_assignments():
    assignments = Assignments.query.all()
    return render_template('assignments/list.html', assignments=assignments)


@assignments.route('/assignment/submit/<int:id>')
def submit(id):
    class_id = request.args.get('class_id', type=int)
    return render_template('assignments/submit_assignment.html', assignment_id=id, class_id=class_id)

@assignments.route('/assignment/submit_assignment', methods=['GET', 'POST'])
def submit_assignment():
    if request.method == 'POST':
        userId = current_user.id
        print("当前用户id", userId)
        file = request.files.get('file')
        assignment_id = request.form.get('assignment_id')
        print("提交作业的文件", file)
        print("提交作业时，当前作业id", assignment_id)

        if file:
            filename = secure_filename(file.filename)
            file_path = os.path.join(current_app.config['UPLOAD_FOLDER2'], filename)

            # 保存文件
            try:
                file.save(file_path)
            except Exception as e:
                return jsonify({'error': str(e)}), 500
        else:
            return jsonify({'error': '文件不能为空'}), 400

        db.session.execute(text("""
                INSERT INTO submissions (assignment_id, student_id, file_path) 
                VALUES (:assignment_id, :userId, :filename)
            """), {'assignment_id': assignment_id, 'userId':userId, 'filename': filename})
        db.session.commit()


        return jsonify({'message': '作业提交成功'}), 200
    return jsonify({'error': 'Invalid request method'}), 405

@assignments.route('/assignment/assignment_status/<int:id>', methods=['GET', 'POST'])
def assignment_status(id):
    class_id = request.args.get('class_id', type=int)  # 班级id
    userId = current_user.id
    userRole = current_user.role
    print(userId)
    print(userRole)

    result = db.session.execute(
        text(
            "select users.id as id, users.username as studentName, submissions.file_path as file_path, submissions.grade as grade from users join sc on users.id = sc.student_id and :classId = sc.class_id left join submissions on users.id = submissions.student_id and :assignmentId = submissions.assignment_id"), {'classId': class_id, 'assignmentId': id}
    ).fetchall()
    db.session.commit()

    return render_template('assignments/assignment_status.html', class_id=class_id, students=result, role=userRole, assignmentId=id)

@assignments.route('/assignment/grade_page/<int:id>', methods=['GET', 'POST'])
def grade_page(id):
    assignmentId = request.args.get('assignmentId', type=int)
    classId = request.args.get('classId', type=int)
    return render_template('assignments/set_grade.html', student_id=id, assignmentId=assignmentId, classId=classId)


@assignments.route('/assignment/set_grade/', methods=['GET', 'POST'])
def set_grade():
    if request.method == 'POST':
        grade = request.form.get('grade')
        assignment_id = request.form.get('assignment_id')
        student_id = request.form.get('student_id')


        db.session.execute(text("""
                update submissions set grade=:grade where submissions.assignment_id = :assignment_id and submissions.student_id = :student_id
            """), {'assignment_id': assignment_id, 'student_id':student_id, 'grade': grade})
        db.session.commit()


        return jsonify({'message': '成绩设置成功'}), 200
    return jsonify({'error': 'Invalid request method'}), 405


